﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Client.Commands;

namespace Client.ViewModels
{
    public class WizardViewModel : BaseViewModel
    {
        #region Init

        private ReadOnlyCollection<WizardPageViewModel> pages;
        private WizardPageViewModel currentPage;

        public WizardViewModel(List<WizardPageViewModel> pages)
        {
            this.pages = new ReadOnlyCollection<WizardPageViewModel>(pages);
            this.currentPage = this.pages[0];

            this.pages[0].OnResult += (m) => this.pages[1].Process(m);
            this.pages[1].OnResult += (m) => this.pages[2].Process(m);
        } 

        #endregion

        #region Properties

        public WizardPageViewModel CurrentPage
        {
            get
            {
                return currentPage;
            }
            private set
            {
                currentPage = value;
            }
        }

        public string ContentButtonNext
        {
            get
            {
                return CurrentPage.GetButtonNextContent();
            }
        }

        #endregion

        #region Navigation

        public ICommand MoveNextCommand
        {
            get
            {
                return new RelayCommand(() => MoveNext(), () => CanMoveNext());
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new RelayCommand(Cancel);
            }
        }

        private void MoveNext()
        {
            var index = pages.IndexOf(CurrentPage);

            if (index == pages.Count - 1)
                OnCompleted();
            else 
            {
                CurrentPage = pages[index + 1];
                NotifyPropertyChanged("CurrentPage");
                NotifyPropertyChanged("ContentButtonNext");
            }
        }

        private bool CanMoveNext()
        {
            if (CurrentPage == null)
                return false;

            return CurrentPage.IsValid();
        }

        private void Cancel()
        {
            var handler = this.OnCancel;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        public event EventHandler OnCancel;

        public event Action OnCompleted;

        #endregion    
    }
}
